package com.zareal.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zareal.domain.Application;
import com.zareal.dot.GetProductDto;
import com.zareal.dot.PutApplicationDto;
import com.zareal.feign.StorageFeignClient;
import com.zareal.mapper.ApplicationMapper;
import com.zareal.result.JSONResult;
import com.zareal.service.IApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Wilson
 * @since 2022-09-28
 */
@Service
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, Application> implements IApplicationService {
    @Autowired
    private ApplicationMapper applicationMapper;

    @Autowired
    private StorageFeignClient storageFeignClient;
    // 提交申请
    @Override
    public JSONResult putApplication(PutApplicationDto putApplicationDto) {
        Application application = putApplicationDtoTOApplication(putApplicationDto);
        applicationMapper.insert(application);
        return JSONResult.success();
    }

    // 申请通过
    @Override
    public JSONResult passApplication(Long id) {
        Application application = applicationMapper.selectById(id);
        // 采购 把state改成1
        application.setState(1L);
        applicationMapper.updateById(application);
        // 调用store接口 入库
        GetProductDto getProductDto = applicationTOGetProductDto(application);
        storageFeignClient.putStorage(getProductDto);
        return JSONResult.success("申请通过,购买成功,产品已入库");
    }
    // 把申请表的内容转换成dto传输到库存
    private GetProductDto applicationTOGetProductDto(Application application) {
        GetProductDto getProductDto = new GetProductDto();
        // 给出产品id给dto
        getProductDto.setId(application.getProductId());
        // 购买数量
        getProductDto.setNumber(Integer.valueOf(application.getNumber().toString()));
        return getProductDto;
    }

    // 拒绝申请
    @Override
    public JSONResult failApplication(Long id) {
        Application application = applicationMapper.selectById(id);
        application.setState(-1L);
        applicationMapper.updateById(application);
        return JSONResult.success("拒绝申请成功");
    }




    // 对象转换
    private Application putApplicationDtoTOApplication(PutApplicationDto putApplicationDto) {
        Application application = new Application();
        application.setProductId(putApplicationDto.getProduct_id());
        application.setNumber(putApplicationDto.getNumber());
        // 待审核0 通过1 拒绝-1
        application.setState(1L);
        application.setTime(new Date());
        return application;
    }
}
